package com.str.list;
public class ArrayList implements List {

  private static final int DEFAULT_SIZE = 10;
  private Object[] array;    // list content
  private int count;

// Constructor
  public ArrayList() {
    array = new Object[DEFAULT_SIZE];
    count = 0;
  }

// Modifiers
  public void clear() {
    for (int i = 0; i < count; i++) array[i] = null;
    count = 0;
  }

  public void add(int i, Object val) {
  // Add x as the element with index i in this list. Throw an
  // IndexOutOfBoundsException if i is out of range.
    if (i < 0 || i > count)
      throw new IndexOutOfBoundsException();
    if (count == array.length) expand();
    for (int j = count; j > i; j--)
      array[j] = array[j-1];
    array[i] = val;
    count++;
  }

  public void add(Object val) {
  // Add x after the last element of this list.
    if (count == array.length) expand();
    array[count++] = val;
  }

  public Object remove(int i) {
  // Remove and return the element with index i in this list, or return null
  // if there is no such element.
    if (i < 0 || i >= count)
      throw new IndexOutOfBoundsException();
    Object val = array[i];
    for (int j=i; j<count-1; j++)
      array[j] = array[j+1]; 
    array[--count] = null;
    return val;
  }

// Accessors 
  public boolean isEmpty() {
  // Return true if and only if this list is empty.
    return count == 0;
  }

  public int size() {
  // Return this list's length.
    return count;
  }
  
  public Object getValue(int i) {
  // Return the element with index i in this list. Throw an
  // IndexOutOfBoundsException if i is out of range..
    if (i < 0 || i >= count)
      throw new IndexOutOfBoundsException();
    return array[i];
  }
    
  public int indexOf(Object val) {
    for (int i = 0; i < count; i++)
      if (val.equals(array[i]))
        return i;
    return -1;
  }
    
// Auxiliary methods  
  private void expand() {
  	Object[] newArray = new Object[2 * array.length];
  	for (int i = 0; i < array.length; i++)
  	  newArray[i] = array[i];
  	array = newArray;
  }
 
  public String toString() {
    String buf = new String("[ ");
    for (int i = 0; i < count; i++) {
   	  if (i > 0) buf += ", ";           
      buf += array[i];
    }
    buf += " ]";
    return buf;
  }
}
